/**
 * @author lonun
 * @blog http://www.lonun.com
 */

var parseURL = require('url').parse,
path = require("path"), 
fs = require('fs'),

Controller = require('./controller').Controller;

exports.getController = function(url, method){
    var method = method ? method.toLowerCase() : 'get';
    var paramStr = null;
    var urlObj = parseURL(url, true);
    // 如果url为：/xx/yy?zz=1 ,则pathname为：/xx/yy
    var pathname = urlObj.pathname;
    var query = urlObj.query;
    if(pathname.charAt(0)=="/"){
    	paramStr = pathname.substring(1);
    }else{
    	paramStr = pathname;
    }
    if(paramStr.charAt(paramStr.length-1)=="/"){
    	paramStr = paramStr.substring(0,paramStr.length-1);
    }
    
    var params = paramStr.split("/");
    var actionParam;
    var subApp = params[0];
    var appPath = "";
    var controllerPath = "";
    var controllerName = "";
    var actionName = "";
    var controller = null;
    var sep = 0;
    for(var i=0;i<params.length;i++){
    	var tempAppPath = path.join(appPath, "app", params[i]);
    	var fullPath = path.join(__dirname, tempAppPath);
    	if(!path.existsSync(fullPath)){
    		fullPath = fullPath+".js";
    		if(path.existsSync(fullPath)){
    			controllerPath = tempAppPath;
    			controllerName = params[i];
    			if(params[i+1]){
    				actionName = params[i+1];
    			}else{
    				actionName = "index";
    			}
    			controller = new Controller(path.join(appPath, "app"), controllerName, actionName);
    			controller.setUrl(url);
    			sep = i;
    			if(params.length=i+2){
    				controller.addParam("key", params[i+1]);
    			}
    			if(query){
					controller.addAllParam("key", params[i+1]);
				}
    			return controller;
    		}else{
    			console.log("没有找到：/"+tempAppPath);
    			return null;
    		}
    	}else{
    		appPath = tempAppPath;
    	}
    }
    console.log("没找到：/"+appPath);
	return null;
    
    /*if(path.exists(appPath)){
    	controllerName = params[1];
    	controllerPath = path.join(appPath, controllerName);
    	if(path.exists(controllerPath)){
    		controller = new Controller(subApp, controllerName, params[2]);
    	}else{
    		console.log("没有找到：/"+params[0]+"/"+params[1]);
    		return null;
    	}
    }else{
    	var controllerPath = path.join(__dirname, "app", params[0]);
    	if(path.exists(controllerPath)){
    		controller = new Controller(null, controllerName, params[1])
    	}else{
    		console.log("没有找到：/"+params[0]+"/"+params[1]);
    		return null;
    	}
    }*/
    /*var m_routes = routes[method];
    for(var i in m_routes){
        //正则匹配
        r.args = m_routes[i].u.exec(pathname);
        if(r.args){
            r.controller = m_routes[i].c;
            r.action = m_routes[i].a;
            r.args.shift(); //第一个值为匹配到的整个url，去掉
            break;
        }
    }*/
    //如果匹配到route，r大概是 {controller:'blog', action:'index', args:['1']}
//    return r;
};